# encoding: utf-8



from ppocronnx.predict_system import TextSystem
from utils.OcrDataUtility import draw_ocr_box_result,get_data_from_image
from utils.ImageUtil import *
import cv2
import requests
from PIL import Image
from PIL.ImageShow import show
import pytesseract
import time

class OcrUtil:
    def __init__(self):
        pass

    @classmethod
    def getTextAreaByAlign(cls,x1,y1,x2,y2):
        img = ImageUtil.cropArea(x1, y1, x2, y2)
        time.sleep(2)
        return cls.getTextAreaByImg(img)

    @classmethod
    def getTextByAlign(cls, x1,y1,x2,y2):
        img = ImageUtil.cropArea(x1, y1, x2, y2)
        return cls.getTextByImg(img)

    @classmethod
    def getTextAreaByImg(cls,img):
        text_sys = TextSystem()
        # 检测并识别文本
        img = cv2.imread(img)
        # img = cv2.resize(img, (0, 0), fx=1.5, fy=1.5, interpolation=cv2.INTER_LINEAR)
        try:
            res = text_sys.detect_and_ocr(img, box_thresh=0.5, unclip_ratio=2)
            data = get_data_from_image(img, res, 0.5, 'simhei.ttf')
            return data
        except:
            return (0,0)
        return (0,0)

    @classmethod
    def getTextByImg(cls, img):
        text_sys = TextSystem()
        # 检测并识别文本
        img = cv2.imread(img)
        # img = cv2.resize(img, (0, 0), fx=1.5, fy=1.5, interpolation=cv2.INTER_LINEAR)
        # res = text_sys.detect_and_ocr(img, box_thresh=0.5, unclip_ratio=2)
        try:
            res = text_sys.detect_and_ocr(img, box_thresh=0.5, unclip_ratio=2)
        except:
            return []

        # print(res)
        result = []
        for boxed_result in res:
            result.append(boxed_result.ocr_text)
        return result

    @classmethod
    def searchText(cls,x1,y1,x2,y2,search_txt):
        all = cls.getTextAreaByAlign(x1,y1,x2,y2)
        for item in all.items():
            txt, boxes = zip(item)
            findstr = txt[0]
            findstr = findstr.replace('（','(').replace('）',')').replace('s','S').replace('+','十')
            print(findstr)
            if findstr.find(search_txt) >= 0:
                if 'box' in boxes:
                    boxdict = boxes['box']
                else:
                    boxdict = boxes[0]
                x = boxdict['box'][0][0]
                y = boxdict['box'][0][1]
                w = boxdict['w']
                h = boxdict['h']
                return (x,y)
        return (0,0)

    @classmethod
    def searchText_2text(cls, x1, y1, x2, y2, search_txt1,search_txt2):
        all = cls.getTextAreaByAlign(x1, y1, x2, y2)
        for item in all.items():
            txt, boxes = zip(item)
            findstr = txt[0]
            # findstr = findstr.replace('（', '(').replace('）', ')').replace('s', 'S')
            print(findstr)
            if findstr.find(search_txt1) >= 0 and findstr.find(search_txt2) >= 0:
                if 'box' in boxes:
                    boxdict = boxes['box']
                else:
                    boxdict = boxes[0]
                x = boxdict['box'][0][0]
                y = boxdict['box'][0][1]
                w = boxdict['w']
                h = boxdict['h']
                return (x, y)
        return (0, 0)

    @classmethod
    def searchModule(cls, x1, y1, x2, y2, search_txt):
        all = cls.getTextAreaByAlign(x1, y1, x2, y2)
        for item in all.items():
            txt, boxes = zip(item)
            findstr = txt[0]
            findstr = findstr.replace('（', '(').replace('）', ')').replace('s', 'S').replace('_', '')
            print(findstr)
            if findstr.find(search_txt) >= 0:
                if 'box' in boxes:
                    boxdict = boxes['box']
                else:
                    boxdict = boxes[0]
                x = boxdict['box'][0][0]
                y = boxdict['box'][0][1]
                w = boxdict['w']
                h = boxdict['h']
                return (x, y)
        return (0, 0)

    @classmethod
    def getTextLinesByAlign(cls,x1,y1,x2,y2):
        img = ImageUtil.cropArea(x1, y1, x2, y2)
        return cls.getTextLinesByImg(img)

    @classmethod
    def getTextLinesByImg(cls,img):
        img = cls.detanchImg(img)
        contents = pytesseract.image_to_string(img, 'chi_sim').split("\n")
        time.sleep(2)
        result = []
        for i in range(0, len(contents)):
            if contents[i].strip() != "":
                line_txt = ' '.join(contents[i].split()).split()
                result.append(line_txt)
        return result

    @classmethod
    def detanchImg(cls,img):
        img2 = cv2.imread(img)
        # 我想把logo放在左上角，所以我创建了ROI
        rows, cols, channels = img2.shape
        # 现在创建logo的掩码，并同时创建其相反掩码
        img2gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
        ret, mask = cv2.threshold(img2gray, 240, 255, cv2.THRESH_BINARY)
        # 仅从logo图像中提取logo区域
        img2_fg = cv2.bitwise_and(img2gray, img2gray, mask=mask)
        return img2_fg

    @classmethod
    def searchSecondText(cls,x1,y1,x2,y2,search_txt,match_type=2):
        all = cls.getTextAreaByAlign(x1,y1,x2,y2)
        x = 0
        y = 0
        if len(all) < 0:
            return (0,0)
        for item in all.items():
            txt, boxes = zip(item)
            findstr = txt[0]
            i = 0
            # print(findstr.find(search_txt))
            # print(findstr)
            # print(search_txt)
            if match_type == 2:
                if findstr.find(search_txt) >= 0:
                    if 'box' in boxes:
                        boxdict = boxes['box']
                    else:
                        boxdict = boxes[0]
                    x = boxdict['box'][0][0]
                    y = boxdict['box'][0][1]
                    w = boxdict['w']
                    h = boxdict['h']
                    break
            else:
                if findstr.find(search_txt) == 0:
                    if 'box' in boxes:
                        boxdict = boxes['box']
                    else:
                        boxdict = boxes[0]
                    x = boxdict['box'][0][0]
                    y = boxdict['box'][0][1]
                    w = boxdict['w']
                    h = boxdict['h']
                    break
        return (x,y)

    @classmethod
    def searchSecondTextTransfer(cls,x1,y1,x2,y2,search_txt,match_type=2):
        all = cls.getTextAreaByAlign(x1,y1,x2,y2)
        x = 0
        y = 0
        if len(all) < 0:
            return (0,0)
        for item in all.items():
            txt, boxes = zip(item)
            findstr = txt[0]
            i = 0
            findstr = findstr.replace("（", "(")
            findstr = findstr.replace("）", ")")
            if match_type == 2:
                if findstr.find(search_txt) >= 0:
                    if 'box' in boxes:
                        boxdict = boxes['box']
                    else:
                        boxdict = boxes[0]
                    x = boxdict['box'][0][0]
                    y = boxdict['box'][0][1]
                    w = boxdict['w']
                    h = boxdict['h']
                    break
            else:
                if findstr.find(search_txt) == 0:
                    if 'box' in boxes:
                        boxdict = boxes['box']
                    else:
                        boxdict = boxes[0]
                    x = boxdict['box'][0][0]
                    y = boxdict['box'][0][1]
                    w = boxdict['w']
                    h = boxdict['h']
                    break
        return (x,y)
